<?php

// convert an input string into it's binary equivalent.
function asc2bin($asciiInput, $byteLength=8) {
	// Numerical data is reverse ASCII, so we need to turn it around
	$asciiRev = strrev($asciiInput);

	$binaryOutput = '';
	$strSize = strlen($asciiRev);

	for($x=0; $x<$strSize; $x++)
	{
		$charBin = decbin(ord($asciiRev{$x}));
		$charBin = str_pad($charBin, $byteLength, '0', STR_PAD_LEFT);
		$binaryOutput .= $charBin;
	}

	return $binaryOutput;
}

// Convert ASCII to signed integer
function asc2sint($asciiInput) {
	$sintOutput = unpack("l",$asciiInput);
	$sintOutput = $sintOutput[1];
	return $sintOutput;
};

// Convert ASCII to unsigned integer (requires asc2bin)
function asc2uint($asciiInput) {
	if ($decimalOutput = bindec(asc2bin($asciiInput))) {
		return $decimalOutput;
	} else {
		return "0";
	}
}

// Convert ASCII to a Hex representation of its string (requires asc2bin)
function asc2hex($asciiInput) {
	if ($hexOutput = bin2hex(asc2bin($asciiInput))) {
		return $hexOutput;
	}
}

// Convert ASCII to a float integer
function asc2float($asciiInput) {
	$floatOutput = unpack("f",$asciiInput);
	return $floatOutput[1];
}

// convert a binary representation of a string back into it's original form.
function bin2asc($binaryInput, $byteLength=8) {
	if (strlen($binaryInput) % $byteLength) {
		return false;
	}
	
	// why run strlen() so many times in a loop? Use of constants = speed increase.
	$strSize = strlen($binaryInput);
	$origStr = '';

	// jump between bytes.
	for($x=0; $x<$strSize; $x += $byteLength) {
		// extract character's binary code
		$charBinary = substr($binaryInput, $x, $byteLength);
		$origStr .= chr(bindec($charBinary)); // conversion to ASCII.
	}

	// Numerical data is reverse ASCII, so we need to turn it around
	$asciiRev = strrev($origStr);

	return $asciiRev;
}

/*
SetEQChecksum taken from crc32.cpp source code, translated to PHP

Original source:
void CRC32::SetEQChecksum(uchar* in_data, int32 in_length)
{
	unsigned long data;
    unsigned long check = 0xffffffff;
	
	assert(in_length >= 4 && in_data);
	
    for(int32 i=4; i<in_length; i++)
    {
        data = in_data[i];
        data = data ^ (check);
        data = data & 0x000000ff;
        check = check >> 8;
        data = CRC32Table[data];
        check = check ^ data;
    }
	
    memcpy(in_data, (char*)&check, 4);
}
*/
function SetEQChecksum($in_data) {
	$in_length = strlen($in_data);
	$check = 0xffffffff;
	for ($i=4; $i<in_length; $i++) {
		$data = $in_data[$i];
		$data = $data XOR ($check);
		$data = $data & 0x000000ff;
		$check = $check >> 8;
		$data = $CRC32Table[$data];
		$check = $check XOR $data;
	};
	return $check;
};

function CreateDropdown($name,$table,$dir="ASC") {
	$padding = "\t\t\t";

	global $db;
	$query_dropdown = "SELECT DISTINCT " . $name . " FROM " . $table . " ORDER BY " . $name . " " . $dir;
//	$query_dropdown = "SELECT " . $name . ", COUNT(" . $name . ") AS num FROM " . $table . " GROUP BY " . $name . " ORDER BY " . $name . " " . $dir;
	$result_dropdown = mysql_query($query_dropdown,$db);
	if ($db_row_dropdown = mysql_fetch_array($result_dropdown)) {
		echo "<select name=\"" . $name . "\" onchange=\"submit()\">\n" . $padding . "<option></option>\n";
		do {
			echo $padding . "\t<option value=\"" . $db_row_dropdown[$name] . "\">" . $db_row_dropdown[$name] . "</option>\n";
		} while ($db_row_dropdown = mysql_fetch_array($result_dropdown));
		echo $padding . "</select>";
	};

};

function CreateResultLimit() {
	echo "<input type=\"text\" size=\"1\" name=\"limit\" value=\"" . $_GET["limit"] . "\"> Per Page\n";
	echo "<input type=\"hidden\" name=\"offset\" value=\"" . $_GET["offset"] . "\">\n";
	echo "<input type=\"hidden\" name=\"sort\" value=\"" . $_GET["sort"] . "\">\n";
	echo "<input type=\"hidden\" name=\"dir\" value=\"" . $_GET["dir"] . "\">\n";
	
	echo "<a href=\"?limit=" . $_GET["limit"] . "&offset=";
	if ($_GET["offset"] - $_GET["limit"] >= 0) {
		echo $_GET["offset"] - $_GET["limit"];
	};
	echo "&sort=" . $_GET["sort"] . "&dir=" . $_GET["dir"] . "\">&lt;&lt;Prev</a>&nbsp;\n";
	
	echo "<a href=\"?limit=" . $_GET["limit"] . "&offset=" . ($_GET["offset"] + $_GET["limit"]) . "&sort=" . $_GET["sort"] . "&dir=" . $_GET["dir"] . "\">Next&gt;&gt;</a>";
	echo "\n";
};

function SortLink($FieldName,$DisplayName="",$DefaultSort="ASC") {
	$Limit = "limit";	// Name of query limit for $_GET
	$Offset = "offset";	// Name of offset for $_GET
	$Sort = "sort";		// Name of sort field for $_GET
	$Dir = "dir";		// Name of sort direction for $_GET
	$DisplayName = str_replace(" ","<br>",$DisplayName);	// Change spaces to HTML line breaks
	if (isset($_GET[$Limit])) {
		$LimitOut = "limit=" . $_GET[$Limit] . "&";
	};
	if ($_GET[$Sort] == $FieldName) {
		if ($_GET[$Dir] == "ASC") {
			$NewDir = "DESC";
		} elseif ($_GET[$Dir] == "DESC") {
			$NewDir = "ASC";
		} else {
			$NewDir = $DefaultSort;
		};
	} else {
		$NewDir = $DefaultSort;
	};
	echo "<a href=\"?" . $LimitOut . $Offset . "=" . $_GET[$Offset] . "&" . $Sort . "=" . $FieldName . "&" . $Dir . "=" . $NewDir . "\">" . $DisplayName . "</a>";
};

function GetItemIcon($itemid,$slotid="",$augslot1=0,$augslot2=0,$augslot3=0,$augslot4=0,$augslot5=0) {
	global $db;
	$query_item = "SELECT Name,bagslots,icon FROM items WHERE id='" . $itemid . "'";
	$result_item = @mysql_query($query_item,$db);
	if ($db_row_item = @mysql_fetch_array($result_item)) {
		$ItemLink = "../items/?id=" . $itemid . "&augslot1=" . $augslot1 . "&augslot2=" . $augslot2 . "&augslot3=" . $augslot3 . "&augslot4=" . $augslot4 . "&augslot5=" . $augslot5;
		echo "<a href=\"" . $ItemLink . "\" target=\"Item\" onclick=\"OpenItem('" . $ItemLink . "')\"><img height=\"40\" width=\"40\" style=\"border: none\" src=\"../images/icons-items/" . $db_row_item[icon] . ".gif\" alt=\"" . $db_row_item[Name] . "\"></a>";
		if ($db_row_item[bagslots] > 0) {
			$ContainerLink = "container.php?id=" . $_GET["id"] . "&slotid=" . $slotid;
			echo "<br><center><font size=\"-2\"><a href=\"" . $ContainerLink . "\" target=\"Container\" onclick=\"OpenContainer('" . $ContainerLink . "')\">Open</a></font></center>";
		};
	} else {
		echo "<img height=\"40\" width=\"40\" src=\"../images/blank.gif\">";
	};
};

function GetItemName($itemid,$slotid="",$augslot1=0,$augslot2=0,$augslot3=0,$augslot4=0,$augslot5=0) {
	global $db;
	$query_item = "SELECT Name,bagslots,icon FROM items WHERE id='" . $itemid . "'";
	$result_item = @mysql_query($query_item,$db);
	if ($db_row_item = @mysql_fetch_array($result_item)) {
		$ItemLink = "../items/?id=" . $itemid . "&augslot1=" . $augslot1 . "&augslot2=" . $augslot2 . "&augslot3=" . $augslot3 . "&augslot4=" . $augslot4 . "&augslot5=" . $augslot5;
		echo "<a href=\"" . $ItemLink . "\" target=\"Item\" onclick=\"OpenItem('" . $ItemLink . "')\">" . $db_row_item["Name"] . "</a>";
		if ($db_row_item[bagslots] > 0) {
			$ContainerLink = "container.php?id=" . $_GET[id] . "&slotid=" . $slotid;
			echo "<br><center><font size=\"-2\"><a href=\"" . $ContainerLink . "\" target=\"Container\" onclick=\"OpenContainer('" . $ContainerLink . "')\">Open</a></font></center>";
		};
	};
};

function GetItemName_return($itemid,$slotid="",$augslot1=0,$augslot2=0,$augslot3=0,$augslot4=0,$augslot5=0) {
	global $db;
	$query_item = "SELECT Name,bagslots,icon FROM items WHERE id='" . $itemid . "'";
	$result_item = @mysql_query($query_item,$db);
	if ($db_row_item = @mysql_fetch_array($result_item)) {
		$ItemLink = "../items/?id=" . $itemid . "&augslot1=" . $augslot1 . "&augslot2=" . $augslot2 . "&augslot3=" . $augslot3 . "&augslot4=" . $augslot4 . "&augslot5=" . $augslot5;
		$return = "<a href=\"" . $ItemLink . "\" target=\"Item\" onclick=\"OpenItem('" . $ItemLink . "')\">" . $db_row_item["Name"] . "</a>";
		if ($db_row_item[bagslots] > 0) {
			$ContainerLink = "container.php?id=" . $_GET[id] . "&slotid=" . $slotid;
			$return .= "<br><center><font size=\"-2\"><a href=\"" . $ContainerLink . "\" target=\"Container\" onclick=\"OpenContainer('" . $ContainerLink . "')\">Open</a></font></center>";
		};
	};
	return $return;
};

function GetContainerSlotInfo($slotid) {
	global $db;
	$slotid2 = (($_GET[slotid] * 10) + 30) + $slotid;
	$query1 = "SELECT * FROM inventory WHERE charid='" . $_GET[id] . "' AND slotid='" . $slotid2 . "'";
	$result1 = mysql_query($query1,$db);
	if ($db_row1 = mysql_fetch_array($result1)) {GetItemIcon($db_row1[itemid],"",$db_row1[augslot1],$db_row1[augslot2],$db_row1[augslot3],$db_row1[augslot4],$db_row1[augslot5]);}
	else {echo "&nbsp;";};
};

function GetCurrAA($aa) {
	global $Profile;
	if(isset($Profile[aa_array][$aa])) {return $Profile[aa_array][$aa];}
	else {return 0;};
};

function GetSlotInfo($slotid) {
	global $db;
	$query_inventory = "SELECT * FROM inventory WHERE charid=" . $_GET["id"] . " AND slotid='" . $slotid . "'";
	$result_inventory = mysql_query($query_inventory,$db);
	if ($db_row1 = mysql_fetch_array($result_inventory)) {GetItemIcon($db_row1[itemid],$slotid,$db_row1[augslot1],$db_row1[augslot2],$db_row1[augslot3],$db_row1[augslot4],$db_row1[augslot5]);}
	else {echo "<img height=\"40\" width=\"40\" src=\"../images/blank.gif\">";};
};

function GetSpellIcon($spell_id) {
	if ($spell_id != 4294967295) {
		global $db;
		global $Profile;
		$spell_name_query = "SELECT name, new_icon FROM spells_new WHERE id=" . $spell_id;
		$spell_name_result = mysql_query($spell_name_query,$db);
		$spell_name_row = mysql_fetch_array($spell_name_result);
		$SpellLink = "../spells/?id=" . $spell_id . "&level=" . $Profile[level];
		return "<a href=\"" . $SpellLink . "\" target=\"Spell\" onclick=\"OpenSpell('" . $SpellLink . "')\"><img height=\"24\" width=\"24\" style=\"border: none\" src=\"../images/icons-spell_gems/" . $spell_name_row[new_icon] . ".gif\" alt=\"" . $spell_name_row[name] . "\"></a>";
	} else {return FALSE;};
};

function GetSpellName($spell_id) {
	if ($spell_id != 4294967295) {
		global $db;
		$spell_name_query = "SELECT name FROM spells_new WHERE id=" . $spell_id;
		$spell_name_result = mysql_query($spell_name_query,$db);
		$spell_name_row = mysql_fetch_array($spell_name_result);
		$SpellLink = "../spells/?id=" . $spell_id;
		return "<a href=\"" . $SpellLink . "\" target=\"Spell\" onclick=\"OpenSpell('" . $SpellLink . "')\">" . $spell_name_row[name] . "</a>";
	} else {return FALSE;};
};

function GetSpellDescription($effectid, $calc = 0, $base1 = 0, $base2 = 0, $max = 0, $low_level = 1, $level = 70) {
	if (!($level > 0)) {$char_level = 70;}
	else {$char_level = $level;};
	$low = GetSpellCalc($calc, $base1, $base2, $max, $low_level);

	switch($effectid) {
		case 0:
			$return = "Increase Hitpoints by " . $low . " (L" . $low_level . ") to " . $max . " (L??).";
			$me = 1;
			break;
		case 27:
			$return = "Cancel Magic (" . $low . ")";
			break;
		case 32:
			$return = "Summon Item: " . GetItemName_return($base1) . " (ID: " . $base1 . ")";
			break;
		case 46:
			$return = "Increase Fire Resist by " . $low . " (L" . $low_level . ") to " . $max . " (L??)";
			$me = 1;
			break;
		default:
			$return = "Unknown Effect ID (" . $effectid . ")";
			break;
	};
	if (($level > 0) && ($me == 1)) $return .= " Me: " . GetSpellCalc($calc, $base1, $base2, $max, $char_level) . " (L" . $char_level . ")";
	return $return;
};

function GetSpellCalc($calc = 0, $base1 = 0, $base2 = 0, $max = 0, $level = 70) {
	switch ($calc) {
		case 0:
		case 100:
			$value = $base1;
			break;
		case 102:
			$value = $base1 + $level;
			break;
		default:
			if ($calc < 100) {$value = $base1 + ($level * $calc);}
			else {$value = "(Unknown Calculation: " . $calc . ")";};
			break;
	}
	if (($value > $max) && ($max != 0)) $value = $max;
	return $value;
};

function GetSpellText($spell_id) {
	if ($spell_id != 4294967295) {
		global $db;
		$q_dbstr = "SELECT text FROM dbstr_us WHERE id1='" . $spell_id . "' AND id2='6'";
		$r_dbstr = mysql_query($q_dbstr,$db);
		$row_dbstr = @mysql_fetch_array($r_dbstr);
		// Insert durations, etc, into the Spell Effect string
			// # = min
			if (preg_match_all("/#[A-Za-z0-9][A-Za-z0-9]?/", $row_dbstr[text], $matches)) {
				foreach ($matches[0] as $value) {
					$num = substr($value, 1);
					$val = abs(@mysql_result(mysql_query("SELECT effect_base_value" . $num . " FROM spells_new WHERE id=" . $spell_id,$db),0));
					$row_dbstr[text] = str_replace($value, $val, $row_dbstr[text]);
				};
			};
			// @ = max
			if (preg_match_all("/@[A-Za-z0-9][A-Za-z0-9]?/", $row_dbstr[text], $matches)) {
				foreach ($matches[0] as $value) {
					$num = substr($value, 1);
					$val = abs(@mysql_result(mysql_query("SELECT max" . $num . " FROM spells_new WHERE id=" . $spell_id,$db),0));
					$row_dbstr[text] = str_replace($value, $val, $row_dbstr[text]);
				};
			};
			// %z = duration
			// abs(@mysql_result(mysql_query("SELECT buffduration FROM spells_new WHERE id=" . $spell_id,$db),0))
			$row_dbstr[text] = str_replace("%z", abs(@mysql_result(mysql_query("SELECT buffduration FROM spells_new WHERE id=" . $spell_id,$db),0)), $row_dbstr[text]);
		return $row_dbstr[text];
	} else {return FALSE;};
};

function GetStatsFromArmor($stat) {
	if (isset($stat)) {
		global $db;
		$query_inventory = "SELECT sum(" . $stat . ") AS " . $stat . " FROM items LEFT JOIN inventory ON items.id=inventory.itemid WHERE charid=" . $_GET[id] . " AND slotid BETWEEN 0 AND 20";
		$result_inventory = mysql_query($query_inventory,$db);
		$db_row_inventory = mysql_fetch_array($result_inventory);
		$inv_stat_value = $db_row_inventory[$stat];
		
		for ($x = 1; $x <= 5; $x++) {
			$query_aug{$x} = "SELECT sum(" . $stat . ") AS " . $stat . " FROM items LEFT JOIN inventory ON items.id=inventory.augslot" . $x . " WHERE charid=" . $_GET[id] . " AND slotid BETWEEN 0 AND 20";
			$result_aug{$x} = mysql_query($query_aug{$x},$db);
			$db_row_aug{$x} = mysql_fetch_array($result_aug{$x});
			$aug_stat_value[$x] = $db_row_aug{$x}[$stat];
		};
		
		$stat_value = $inv_stat_value + $aug_stat_value[1] + $aug_stat_value[2] + $aug_stat_value[3] + $aug_stat_value[4] + $aug_stat_value[5];
		return $stat_value;
	} else {
		return false;
	};
};

function OutputItemStats ($FieldName,$DisplayName="",$Unit="") {
	global $db_row;
	if ($DisplayName == "") {$DisplayName = ucfirst($FieldName);};
	if ($db_row[$FieldName] > 0) {return $DisplayName . ": +" . $db_row[$FieldName] . $Unit . " ";}
	elseif ($db_row[$FieldName] < 0) {return $DisplayName . ": -" . $db_row[$FieldName] . " ";};
};

?>